package com.lsy.jetpackdemo

import androidx.annotation.MainThread
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import java.util.concurrent.atomic.AtomicBoolean

/**
 * @Author Lsy
 * @Date 2022/10/12 10:01
 * 解决粘性事件
 */
class SingleLiveEvent<T> : MutableLiveData<T>() {
    private var mPending = AtomicBoolean(false)

    override fun observe(owner: LifecycleOwner, observer: Observer<in T>) {
        super.observe(owner, {
            if (mPending.compareAndSet(true,false)) {
                observer.onChanged(it)
            }
        })
    }

    @MainThread
    override fun postValue(value: T) {
        mPending.set(true)
        super.postValue(value)
    }

    @MainThread
    fun call() {
        value = null
    }

}